<template>
  <div style="height: 100%;">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :key="index" v-for="(item, index) in breadcrumbItems">{{ item }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="table-wrap-box">
      <el-container>
        <el-aside class="side-wrap" width="220">
          <SideCategoryMenu :categoriesTree="categoryTreeData" @add-btn-click="addCategory" @del-btn-click="delCategory"
            @edit-btn-click="editCategory" @tree-node-click="treeNodeClickHandler"
            @tree-node-cancel-check="treeNodeCancelCheckHandler" @setting-btn-click="settingBtnClickHandler" />
        </el-aside>
        <el-main class="main-wrap">
          <div style="width: 160px;display: flex;justify-content: space-around;margin-bottom: 4px">
            <el-button size="mini" @click="saveTableData">
              <svg-icon class-name="svg-icon" icon-class="save"></svg-icon>
              保存
            </el-button>
            <el-button size="mini" icon="el-icon-plus" type="primary" @click="addRowClick">新增</el-button>
            <el-button icon="el-icon-delete" size="mini" type="danger" @click="delBatchClickHandler">删除</el-button>
            <!-- <el-button icon="el-icon-download" size="mini" type="primary" @click="downloadTemplateHandler">下载模板</el-button> -->
            <el-button icon="el-icon-upload" size="mini" type="primary" @click="batchImportHandler">批量导入</el-button>
          </div>
          <el-table :data="libraryTableData" :max-height="800" :border=true fit row-key="id" size="mini" 
            style="width: 100%" @selection-change="rowSelectChangeHander">
            <el-table-column type="selection" v-if="showSelectionColumn">

            </el-table-column>

            <el-table-column v-if="showSelectionColumn" v-for="(field, key) in featureFieldList" :key="field.id"
              :label="field.label" align="center">
              <template slot-scope="scope">
                <span v-if="field.oper">
                  <el-button type="text" size="mini" @click="rowEditClickHandler(scope.row)">编辑</el-button>
                  <el-button type="text" size="mini">详情</el-button>
                  <el-button type="text" size="mini" style="color: #f56c6c" @click="rowDeleteHandler(scope.row)">删除</el-button>
                </span>
                <template v-else>
                  <template v-if="scope.row.editState">
                  <el-date-picker style="width: 140px;" v-if="field.viewType === 'date'" size="mini"
                    v-model="scope.row[field.name]"></el-date-picker>
                  <el-input size="mini" v-else v-model="scope.row[field.name]"></el-input> 
                </template>
                <span v-else>
                  {{ scope.row[field.name] }}
                </span>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </el-card>
  </div>
</template>

<script>

import SideCategoryMenu from '@/components/feature/SideCategoryMenu.vue';
import '@/assets/css/featureLayout.css';
import LibraryCategoryForm from '@/components/library/LibraryCategoryForm.vue';
import LibrarySettingForm from '@/components/library/LibrarySettingForm';
import LibraryDataAddForm from '@/components/library/LibraryDataAddForm.vue';
import FileUploadForm from '@/components/common/FileUploadForm.vue';
import { useFormDialog } from '@/components/formDialog/FormDialog';
import { $LibraryCategoryApi } from '@/network/library/LibraryCategoryApi';
import { $FeatureFiledApi } from "@/network/feature/FeatureFieldApi";
import { $LibrarySettingApi } from '@/network/library/LibrarySettingApi';
import { $LibraryDataApi } from '@/network/library/LibraryDataApi';

export default {
  name: 'Library',
  components: { SideCategoryMenu },
  data() {
    return {
      breadcrumbItems: [],
      categoryTreeData: [],
      featureFieldList: [],
      libraryTableData: [],
      selectCateNode: null,   // 选择的目录节点
      sideMenuId: '',
      settingMap: {},
      rowForm: {},
      rowEdit: false,
      showOperColumn: true,
      checkedRows: [],      // 勾选的行
    }
  },

  methods: {
    addCategory() {
      useFormDialog({
        title: "新增节点",
        parentId: this.selectCateNode?.id,
        parentName: this.selectCateNode?.name,
      }, LibraryCategoryForm, async (data) => {
        data.menuId = this.sideMenuId;
        const res = await $LibraryCategoryApi.addNode(data);
        this.ShowMessage(res);
        this.loadCategoryData();
      }, () => {
        this.$message.info("取消操作");
      });
    },

    delCategory() {
      if (!this.selectCateNode) {
        this.$message.info("请选择要删除的节点");
      } else {
        let nodeLabel = this.selectCateNode.label !== null ? this.selectCateNode.label : this.selectCateNode.name;
        let msg = '确定删除选择的节点: ' + '"' + nodeLabel + '"';
        this.$confirm(msg, "提示").then(async () => {
          const res = await $LibraryCategoryApi.removeNode({ nodeId: this.selectCateNode.id });
          this.ShowMessage(res);
          this.loadCategoryData();
        }).catch(err => {
          this.$message.info("取消操作!");
        })
      }
    },

    // 编辑类目
    editCategory() {

    },

    // 左侧菜单栏设置按钮点击
    settingBtnClickHandler() {
      if (!this.selectCateNode) {
        this.$message.info("请选择节点");
        return;
      }

      useFormDialog({
        title: "设置",
        nodeId: this.selectCateNode.id,
        nodeName: this.selectCateNode.name,
        nodeType: this.selectCateNode.type,
      }, LibrarySettingForm, async (data) => {
        const { settingId, settingInfo } = data;
        let params = Object.assign({
          id: settingId,
          nodeId: this.selectCateNode.id,
          content: JSON.stringify(settingInfo)
        })
        const res = await $LibrarySettingApi.saveSetting(params);
        this.ShowMessage(res);
        this.loadTableSettings();
      }, () => {
        this.$message.info('取消操作');
      })

    },

    async treeNodeClickHandler(node) {
      this.selectCateNode = node;
      if (node.type === 'feature') {
        const { featureId } = { ...node };
        let res = await $FeatureFiledApi.listByFeatureId({ featureId })
        this.featureFieldList = res.data;
        this.featureFieldList.push({
          label: '操作',
          oper: true
        })
        // 获取表格设置
        this.loadTableSettings();
        // 获取数据列表
        this.loadTableData();
      }
    },

    treeNodeCancelCheckHandler() {
      this.selectCateNode = null;
      this.showOperColumn = false;
    },

    
    /**
     * 表格行选中事件处理
     */
    rowSelectChangeHander(selection, row) {
      this.checkedRows = selection;
    },

    // 加载分类树
    async loadCategoryData() {
      const res = await $LibraryCategoryApi.listLibraryCategoryTree();
      this.categoryTreeData = res.data;
    },

    // 获取表格配置
    async loadTableSettings() {
      let node = this.selectCateNode;
      if (!node || node.type !== 'feature') {
        this.$message.error("请选择知识对象节点");
      }
      const resp = await $LibrarySettingApi.getByNodeId({ nodeId: node.id });
      const { settingsMap } = resp.data;
      this.settingMap = settingsMap;
    },

    // 表格添加行
    async addRowClick() {
      if (!this.selectCateNode) {
        this.$message.info("请选择知识对象节点");
        return;
      }
      this.showOperColumn = true;
      if (this.isShowDialog) {
        // 弹窗新增
        useFormDialog({

        }, LibraryDataAddForm, () => {

        }, () => {
          this.$message.info("用户取消操作");
        });
      } else {
        // 表格新增行
        let rowNum = this.libraryTableData.length + 1;
        this.libraryTableData.push(
          { 
            editState: true, 
            rowNum: rowNum,
          }); 
      }
    },

    // 表格上方批量删除
    delBatchClickHandler() {
      if (this.checkedRows.length === 0) {
        this.$message.info("请选择要删除的行");
      }
      this.$confirm("确定删除选中的数据?", "提示", {type: 'warning'}).then(async () => {
        const ids = this.checkedRows.map(row => row.id);
        const res = await $LibraryDataApi.batchRemove({
          ids: ids,
          nodeId: this.selectCateNode.id,
          recordId: this.selectCateNode.recordId,
          featureId: this.selectCateNode.featureId,
        });
        this.ShowMessage(res);
        this.loadTableData();
      });

    },

    // 行删除
    rowDeleteHandler(row) {
      this.$confirm("确定删除当前数据?", "提示", {type: 'warning'}).then(async () => {
        const ids = [row.id];
        const res = await $LibraryDataApi.batchRemove({
          ids: ids,
          nodeId: this.selectCateNode.id,
          recordId: this.selectCateNode.recordId,
          featureId: this.selectCateNode.featureId,
        });
        this.ShowMessage(res);
        this.loadTableData();
      });
    },

    // 保存表格数据
    async saveTableData() {
      if (!this.selectCateNode) {
        return;
      }
      const rowData = this.libraryTableData.filter(item => item.editState);
      console.log("rowData = ", rowData);
      const params = {
        nodeId: this.selectCateNode.id,
        recordId: this.selectCateNode.recordId,
        rowData: [...rowData],
        featureId: this.selectCateNode.featureId,
      }
      const res = await $LibraryDataApi.batchSaveLibraryData(params);
      this.ShowMessage(res);
      this.loadTableData();
    },

    // 加载表格数据
    async loadTableData() {
      const { id: nodeId, recordId, featureId } = this.selectCateNode;
      const res = await $LibraryDataApi.queryDataList({
        nodeId,
        recordId,
        featureId
      });
      this.libraryTableData = res.data;
    },

    // 行编辑
    rowEditClickHandler(row) {  
      let id = row.id;
      let target = this.libraryTableData.find(item => item.id === id);
      if (target) {
        this.$set(target, 'editState', true);
      }
    },

    // 下载模板
    async downloadTemplateHandler() {
      // todo
      if (!this.selectCateNode) {
        this.$message.info("请选择知识对象节点!");
        return;
      }
      const { id: nodeId, recordId, featureId } = this.selectCateNode;
      await $LibraryDataApi.downloadTemplate({
        recordId,
        featureId
      });      
    },

    // 批量导入数据
    batchImportHandler() {
      if (!this.selectCateNode) {
        this.$message.info("请选择知识对象节点!");
        return;
      }
      useFormDialog({
        title: '批量导入',
        width: '500px',
        node: {...this.selectCateNode}
      }, FileUploadForm, (data) => {

      }, () => {
        this.$message.info('取消操作');
      })
    }


  },

  computed: {
    // 是否展示单选列
    showSelectionColumn() {
      return this.selectCateNode !== null && this.selectCateNode.type === 'feature'
        && this.featureFieldList.length > 0;
    },

    isShowDialog() {
      return this.settingMap.TableDataAddMode?.value === 'dialog';
    },



  },

  watch: {
    $route: {
      handler: function (newRoute, oldRoute) {
        this.breadcrumbItems = ['知识中心', newRoute.meta.description];
        this.curKind = newRoute.meta.name;
        this.sideMenuId = newRoute.meta.id;
      },
      immediate: true,
      deep: true
    },



  },

  mounted() {
    this.loadCategoryData();
  },


}

</script>